package com.itheima.controller;

import com.itheima.domain.Admin;
import com.itheima.domain.PageBean;
import com.itheima.domain.ResultMsg;
import com.itheima.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    //管理员登录
    @RequestMapping("/login")
    @ResponseBody
    public ResultMsg login(String username, String password){
        Admin admin = adminService.findByUsernameAndPassword(username, password);
        ResultMsg resultMsg = new ResultMsg();
        if (admin!=null){
//            System.out.println("登录成功");
            resultMsg.setAdmin(admin);
            resultMsg.setFlag(true);
        }else{
//            System.out.println("登录失败");
            resultMsg.setErrorMsg("用户名或密码错误,请重试!");
            resultMsg.setFlag(false);
        }
        return resultMsg;
    }

    //管理员展示
    @RequestMapping("/findAll")
    public String findAll(String rows, String currentPage, HttpServletRequest httpServletRequest){
        if (currentPage==null||"".equals(currentPage)){
            currentPage="1";
        }
        if (rows==null||"".equals(rows)){
            rows="5";
        }
        PageBean<Admin> pb = adminService.findAll(currentPage,rows);
        httpServletRequest.setAttribute("pb",pb);
        return "admin";
    }

    //管理员添加
    @RequestMapping("/saveAdmin")
    @ResponseBody
    public Boolean findAll(Admin admin){
        if (admin==null){
            return false;
        }else{
            adminService.saveAdmin(admin);
        }
        return true;
    }

    //寻找重名管理员
    @RequestMapping("/findByUsernane")
    @ResponseBody
    public ResultMsg findByUsername(String username){
        ResultMsg resultMsg = new ResultMsg();
        if (username==null||username.length()==0){
            resultMsg.setFlag(true);
            resultMsg.setErrorMsg("请填写用户名");
//            System.out.println("请填写用户名");
        }else{
            Admin admin = adminService.findByUsername(username);
            if (admin!=null){
                resultMsg.setFlag(true);
                resultMsg.setErrorMsg("用户名重复");
//                System.out.println("用户名重复");
            }else{
                resultMsg.setFlag(false);
                resultMsg.setErrorMsg("用户名可用");
//                System.out.println("用户名可用");
            }
        }
        return resultMsg;
    }
    //管理员添加
    @RequestMapping("/delAdminById")
//    @ResponseBody
    public String delAdminById(String aid){
        adminService.deleteByAid(Integer.parseInt(aid));
        return "forward:findAll";
    }
}
